<?php

namespace addons\shopro\controller;


/**
 * 助力砍活动接口
 *
 */

class ActivityBargain extends Base
{
    protected $noNeedLogin = ['index','detail','givegift','signtravel','test','getgiftorder','littledetail'];
    protected $noNeedRight = ['*'];

    protected $model = null;



    /**
     * 获取所有礼包
     */
    public function index() {
        $user_bargain_list = [];
        $bargain_list = \addons\shopro\model\ActivityBargain::getActivityBargainProducts();

        $user = $this->auth->getUserInfo();
        //$user = db('user')->find(4);
        if($user){
            //有用户登录
            $id   = $user['id'];
            //找到该用户的砍价列表
            $w = [
                'user_id'      => $id,
                //'invalid_time' => ['gt',time()],
                //'is_addorder'  => 0,
            ];
            $user_bargain = db('shopro_activity_bargainirg')
                ->where($w)
                ->select();

            $nowtime = time();
            foreach ($bargain_list as $k=>$p){
                foreach ($user_bargain as $ub){
                    if($ub['activity_bargain_id'] == $p['id']){

                        if($ub['invalid_time'] >= $nowtime && $ub['is_addorder'] == 0){
                            //加入$user_bargain_list
                            $p['bargainirg'] = $ub;
                            $p['cut_total_money'] = $ub['cut_total_money'];
                            $user_bargain_list[] = $p;
                        }
                        //unset($bargain_list[$k]);
                        break;
                    }
                }
            }

        }

        $ret = [
            'user_bargain_list' =>   $user_bargain_list,
            'bargain_list' => $bargain_list
        ];

        $this->success('助力砍列表', $ret);
    }

    /**
     * 礼包详情
     */
    public function detail() {
        $bargain_id = $this->request->get('bargain_id');

        $goods_id = $this->request->get('goods_id');
        $detail = \addons\shopro\model\Goods::getGoodsDetail($goods_id);

        // 记录足记
        //\addons\shopro\model\UserView::addView($detail);

        $sku_price = $detail['sku_price'];      // 处理过的规格
        // tp bug json_encode 或者 toArray 的时候 sku_price 会重新查询数据库，导致被处理过的规格又还原回去了
        $detail = json_decode(json_encode($detail), true);
        $detail['sku_price'] = $sku_price;


        //////////////////////////////////查询已经成功的数量
        $bargain = db('shopro_activity_bargain')->where(['id'=>$bargain_id,'goods_id'=>$goods_id])->find();
        if(empty($bargain)){
            $this->error('砍价商品不存在');
        }
        $detail['bargain_success_num'] = $bargain['success_num'] ?? 0;
        $detail['is_bargain'] = 0;//0-未砍价 1-砍价中
        $detail['bargain_id'] = $bargain_id;
        $detail['activity_min_price'] = $bargain['activity_min_price'];
        $detail['bargain'] = $bargain;
        //是否是砍价中
        $user = $this->auth->getUserInfo();
        if($user) {
            //有用户登录
            $id = $user['id'];
            //找到该用户的砍价列表
            $w = [
                'activity_bargain_id'=>$bargain_id,
                'goods_id' => $goods_id,
                'user_id' => $id,
                'invalid_time' => ['gt', time()],
                'is_addorder' => 0,
            ];
            $user_bargain = db('shopro_activity_bargainirg')
                ->where($w)
                ->find();

            if($user_bargain){
                $detail['is_bargain'] = 1;
                $detail['bargainirg'] = $user_bargain;

                ////////////////用户帮助列表
                $assistor_list = \addons\shopro\model\ActivityBargain::getAssistorList($user_bargain['id']);
                $detail['assistor_list'] = $assistor_list;
            }
        }

        $this->success('商品详情', $detail);
    }

    /**
     * 报名砍价接口
     */
    public function beginToBargain()
    {
        if(!request()->isPost()){
            $this->error('需要POST请求');
        }
        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $this->error('用户未登录,请先登录.');
        }

        $bargain_id     = $this->request->param('bargain_id');
        $goods_id       = $this->request->param('goods_id');
        $user_addr_id   = $this->request->param('user_addr_id');

        $bargain = db('shopro_activity_bargain')->where(['id'=>$bargain_id,'goods_id'=>$goods_id,'deletetime'=>null])->find();
        if(empty($bargain)){
            $this->error('商品不存在.');
        }

        $deal_money = $bargain['activity_price']-$bargain['activity_min_price'];
        $this->success('报名砍价', \addons\shopro\model\ActivityBargain::beginToBargain($bargain_id,$goods_id,$user['id'],$deal_money,$bargain['activity_min_price'],$bargain['valid_time'],$user_addr_id));
    }

    /**
     * 继续砍价界面数据
     */
    public function myBargainGoods()
    {
        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $this->error('用户未登录,请先登录.');
        }

        $bargainirg_id =$this->request->param('bargainirg_id');
        $bargainirg = db('shopro_activity_bargainirg')
            ->field('ab.*,goods.title as goods_title,goods.image')
            ->alias('ab')
            ->join('shopro_goods goods','ab.goods_id = goods.id')
            ->where(['ab.id'=>$bargainirg_id,'user_id'=>$user['id']])
            ->find();
        if(empty($bargainirg)){
            $this->error('砍价商品不存在.');
        }

        if($bargainirg['cut_total_money'] >= round($bargainirg['activity_price'] - $bargainirg['activity_min_price'],2)){
            if($bargainirg['is_addorder'] == 0){
                $bargainirg['status'] = 2;//砍价成功可以领取奖品

                $goods_id = $bargainirg['goods_id'];
                $sku = db('shopro_goods_sku_price')->where(['goods_id'=>$goods_id])->find();
                $goods_list = [[
                    'goods_id'      => $bargainirg['goods_id'],
                    "goods_num"     => 1,
                    'goods_price'   => $bargainirg['activity_min_price'],
                    'dispatch_type' => "express",
                    "sku_price_id"  => $sku['id'],
                ]];
                $orderdata['goods_list'] = $goods_list;
                $orderdata['from'] = "goods";
                $orderdata['address_id'] = $bargainirg['user_addr_id'];
                $orderdata['order_type'] = "goods";
                $orderdata['buy_type'] = "bargain";
                $orderdata['coupons_id'] = "";
                $orderdata['groupon_id'] = "";
                $orderdata['share_user_id'] = "";
                $orderdata['remark'] = "";
                $bargainirg['orderdata'] = $orderdata;
            }else{
                $bargainirg['status'] = 3;//砍价成功并且已经领取了
            }
        }elseif($bargainirg['invalid_time'] < time() ){
            $bargainirg['status'] = -1;//失效过期失败
        }else{
            $bargainirg['status'] = 1;//喊朋友砍价
        }

        $bargainirg['image'] = cdnurl($bargainirg['image'], true);
        $ret['bargainirg'] = $bargainirg;


        ////////////////用户帮助列表
        $assistor_list = \addons\shopro\model\ActivityBargain::getAssistorList($bargainirg['id']);
        $ret['assistor_list'] = $assistor_list;

        //助力砍
        $bargain = $bargain = db('shopro_activity_bargain')->where(['id'=>$bargainirg['activity_bargain_id']])->find();
        $ret['bargain'] = $bargain;
        $this->success('砍价详情',$ret);

    }

    /**
     * 其他人分享的助力砍商品界面数据
     */
    public function otherBargainGoods()
    {
        $share_user_id =$this->request->param('share_user_id');
        if(empty($share_user_id)){
            $this->error('请传参share_user_id');
        }

        $bargainirg_id =$this->request->param('bargainirg_id');
        $bargainirg = db('shopro_activity_bargainirg')
            ->field('ab.*,goods.title as goods_title,goods.image')
            ->alias('ab')
            ->join('shopro_goods goods','ab.goods_id = goods.id')
            ->where(['ab.id'=>$bargainirg_id,'user_id'=>$share_user_id])
            ->find();
        if(empty($bargainirg)){
            $this->error('砍价商品不存在.');
        }

        $bargainirg['image'] = cdnurl($bargainirg['image'], true);

        ////////////////用户帮助列表
        $assistor_list = \addons\shopro\model\ActivityBargain::getAssistorList($bargainirg['id']);
        $ret['assistor_list'] = $assistor_list;

        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $bargainirg['is_self'] = 0;//自己打开自己的分享页面,自己不能砍价
            $bargainirg['is_cut'] = 0;
            $bargainirg['cut_money'] = 0;
            $ret['bargainirg'] = $bargainirg;

            $this->success('砍价详情',$ret);
        }

        //查看是否帮忙砍过,0-未砍过,非0砍过
        $cut_money = 0;
        $is_cut = 0;
        if($share_user_id != $user['id']){
            foreach ($assistor_list as $item){
                if($item['assistor_user_id'] == $user['id']){
                    $cut_money = $item['bargain_money'];
                    $is_cut = 1;
                    break;
                }
            }

        }
        $bargainirg['is_self'] = $share_user_id == $user['id'] ? 1 : 0;//自己打开自己的分享页面,自己不能砍价
        $bargainirg['is_cut'] = $is_cut;
        $bargainirg['cut_money'] = $cut_money;


        /////////////////判断活动状态
        if($share_user_id == $user['id']){
            $status = 1;//己打开自己的分享页面,自己不能砍价
        }elseif($bargainirg['cut_total_money'] >= round($bargainirg['activity_price'] - $bargainirg['activity_min_price'],2)){
            if($bargainirg['is_addorder'] == 1 && $is_cut){
                $status = 2;//恭喜获得补贴金￥{{tea.bargainirg.cut_money}}元即将转入钱包
            }elseif($bargainirg['is_addorder'] == 0 && $is_cut){
                $status = 3;//已助力,补贴金xxx元,即将转入钱包
            }else{
                $status = 4;//谢谢参与,该商品已助力成功
            }
        }elseif($bargainirg['invalid_time'] < time()){
            $status = 5;//此次助力已失效
        }else{
            if($is_cut){
                $status = 3;//已助力,补贴金xxx元,即将转入钱包
            }else{
                $status = 0;//可以参与一次助力
            }
        }
        $bargainirg['status'] = $status;


        //助力砍
        $bargain = db('shopro_activity_bargain')->where(['id'=>$bargainirg['activity_bargain_id']])->find();
        $ret['bargain'] = $bargain;
        $ret['bargainirg'] = $bargainirg;
        $this->success('砍价详情',$ret);

    }

    /**
     * 帮忙砍一刀
     */
    public function helpcut()
    {
        if(!request()->isPost()){
            $this->error('需要POST请求');
        }

        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $this->error('用户未登录,请先登录.');
        }

        $share_user_id =$this->request->param('share_user_id');
        if(empty($share_user_id)){
            $this->error('请传参share_user_id');
        }

        if($share_user_id == $user['id']){
            $this->error('不能给自己砍价');
        }

        $bargainirg_id =$this->request->param('bargainirg_id');
        $bargainirg = db('shopro_activity_bargainirg')
            ->field('ab.*,goods.title as goods_title,goods.image')
            ->alias('ab')
            ->join('shopro_goods goods','ab.goods_id = goods.id')
            ->where(['ab.id'=>$bargainirg_id,'user_id'=>$share_user_id])
            ->find();
        if(empty($bargainirg)){
            $this->error('砍价商品不存在.');
        }

        ////////////////用户帮助列表
        $assistor_list = \addons\shopro\model\ActivityBargain::getAssistorList($bargainirg['id']);
        $ret['assistor_list'] = $assistor_list;

        //查看是否帮忙砍过,0-未砍过,非0砍过
        $cut_money = 0;
        $is_cut = 0;
        foreach ($assistor_list as $item){
            if($item['assistor_user_id'] == $user['id']){
                $cut_money = $item['bargain_money'];
                $is_cut = 1;
                break;
            }
        }

        if($is_cut){
            $this->error('您已帮伙伴砍掉' . $cut_money . '元啦，不要再砍啦!');
        }
        
        $bargain = db('shopro_activity_bargain')->find($bargainirg['activity_bargain_id']);
        //商品库存
        if($bargain['stock_num']<=0){
            $this->error('已抢光!');
        }

        //判断是否是最低价了
        if($bargainirg['cut_total_money'] >= $bargain['activity_min_price']){
            $this->error('已经最低价啦，不能再砍啦！');
        }

        ///////////////////开始砍价///////////////////////////

        $join_count = $bargain['join_count'];               //设置砍价次数

        //$state = \addons\shopro\model\ActivityBargain::givePartBargain($bargainirg_id,$share_user_id,$user,$min,$max,$join_count);
        $state = \addons\shopro\model\ActivityBargain::avgBargain($bargainirg_id,$share_user_id,$user,
            $bargain['cut_money'],$join_count);

        if ($state == -1) {
            $this->error('已经最低价啦，不能再砍啦！');
        }elseif ($state === false) {
            $this->error('哎呀，失败了！稍后帮我砍一次！');
        } else {
            $this->success('成功帮伙伴砍掉' . $state .'元!', ['cut_money' => $state]);
        }

    }

    /**
     * 砍价成功领取按钮接口
     */
    public function addOrder()
    {
        $this->error('接口已废除.');
        $user = $this->auth->getUserInfo();
        if(empty($user)){
            $this->error('用户未登录,请先登录.');
        }

        $bargainirg_id =$this->request->param('bargainirg_id');
        $bargainirg = db('shopro_activity_bargainirg')
            ->field('ab.*,goods.title as goods_title,goods.image')
            ->alias('ab')
            ->join('shopro_goods goods','ab.goods_id = goods.id')
            ->where(['ab.id'=>$bargainirg_id,'user_id'=>$user['id']])
            ->find();
        if(empty($bargainirg)){
            $this->error('砍价商品不存在.');
        }

        if($bargainirg['cut_total_money'] >= $bargainirg['activity_price']){
            if($bargainirg['is_addorder'] == 1){
                $this->error('砍价成功并且已经领取了');
            }
        }else{
            $this->error('砍价未完成,请喊朋友砍价.');
        }

        //更改状态
        db('shopro_activity_bargainirg')->where('id',$bargainirg_id)->update(['is_addorder'=>1]);

        ///////////////////////开始领取,创建订单
        ///{
        //	"goods_list": [{
        //		"goods_id": 198,
        //		"goods_num": 1,
        //		"goods_price": "198.00",
        //		"sku_price_id": 329,
        //		"dispatch_type": "express"
        //	}],
        //	"from": "goods",
        //	"address_id": 3,
        //	"coupons_id": 0,
        //	"remark": "",
        //	"order_type": "goods",
        //	"buy_type": "",
        //	"groupon_id": "0",
        //	"share_user_id": "16"
        //}
        //{
        //	"goods_list": [{
        //		"goods_id": 191,
        //		"goods_num": 1,
        //		"sku_price_id": 322,
        //		"goods_price": "0.10",
        //		"dispatch_type": "express"
        //	}],
        //	"from": "goods",
        //	"address_id": 3,
        //	"coupons_id": 0,
        //	"remark": "",
        //	"order_type": "goods",
        //	"buy_type": "groupon",
        //	"groupon_id": "0",
        //	"share_user_id": "0"
        //}

        $goods_id = $bargainirg['goods_id'];
        $sku = db('shopro_goods_sku_price')->where(['goods_id'=>$goods_id])->find();
        $goods_list = [[
            'goods_id'      => $bargainirg['goods_id'],
            "goods_num"     => 1,
            'goods_price'   => 0,
            'dispatch_type' => "express",
            "sku_price_id"  => $sku['id'],
        ]];
        $orderdata['goods_list'] = $goods_list;
        $orderdata['from'] = "goods";
        $orderdata['address_id'] = $bargainirg['user_addr_id'];
        $orderdata['order_type'] = "goods";
        $orderdata['buy_type'] = "bargain";
        $orderdata['coupons_id'] = "";
        $orderdata['groupon_id'] = "";
        $orderdata['share_user_id'] = "";
        $orderdata['remark'] = "";

        $order = \addons\shopro\model\Order::createOrder($orderdata);

        //TODO 修改成已支付状态
        $order_sn = $order['order_sn'];
        $orderPay = \addons\shopro\model\Order::nopay()->where('order_sn', $order_sn)->find();
        $orderPay->status = \addons\shopro\model\Order::STATUS_PAYED;
        $orderPay->paytime = time();
        $orderPay->save();

        $this->success("领取成功");
    }

    /**
     * 获取我的助力砍列表
     */
    public function myBargainList() {
        //all,ing,finish
        $type = request()->param('type','all');

        $user = $this->auth->getUserInfo();
        $bargain_list = \addons\shopro\model\ActivityBargain::getBargainListByUserId($user['id']);

        $nowtime = time();
        foreach ($bargain_list as $k=>$p){
            if($p['invalid_time'] > $nowtime && $p['deal_money'] > 0){
                $bargain_list[$k]['status'] = 'ing';
            }elseif($p['invalid_time'] < $nowtime && $p['deal_money'] > 0){
                $bargain_list[$k]['status'] = 'invalid';
            }elseif($p['deal_money'] == 0){
                $bargain_list[$k]['status'] = 'finish';
            }else{
                $bargain_list[$k]['status'] = 'none';
            }

            if($bargain_list[$k]['status'] != $type && $type != 'all'){
                unset($bargain_list[$k]);
            }
        }


        $bargain_list = array_values($bargain_list);

        $this->success('助力砍列表', $bargain_list);
    }
}
